import { deleteShopping, getShoppingList, updateShopping } from "../../services/shopping"

export default {
	namespaced: true,
	state() {
		return {
			cartList: []
		}
	},
	mutations: {
		setCartList(state, newList) {
			state.cartList = newList
		},
		toggleCheck(state, goodId) {
			// 让对应的 id 的项 状态取反
			const good = state.cartList.find(item => item.good_id === goodId)
			good.isChecked = !good.isChecked
		},
		toggleAllCheck(state, flag) {
			// 让所有的小选框，同步设置
			state.cartList.forEach(item => {
				item.isChecked = flag
			})
		},
		changeCount(state, { num, goodId }) {
			const good = state.cartList.find(item => item.good_id === goodId)
			good.num = num
		}
	},
	actions: {
		async getCartAction(context) {
			const res = await getShoppingList()
			// 后台返回的数据中，不包含复选框的选中状态，为了实现将来的功能
			// 需要手动维护数据，给每一项，添加一个 isChecked 状态 (标记当前商品是否选中)
			res.successMessage.forEach(item => {
				item.isChecked = true
			})
			context.commit('setCartList', res.successMessage)
		},
		async changeCountAction (context, obj) {
			const { num, goodId } = obj
		    // 先本地修改
		    context.commit('changeCount', { num, goodId })
		    // 再同步到后台
		    await updateShopping(obj)
		},
		// 删除单个购物车数据
		async delSelect (context, id) {
		    // const selCartList = context.getters.selCartList
		    // const cartIds = selCartList.map(item => item.id)
		    await deleteShopping(id)
		    // toast('删除成功')
		    // 重新拉取最新的购物车数据 (重新渲染)
		    await context.dispatch('getCartAction')
		}
	},
	getters: {
	    // 求所有的商品累加总数
	    cartTotal (state) {
	      return state.cartList.reduce((sum, item) => sum + item.num, 0)
	    },
	    // 选中的商品项
	    selCartList (state) {
	      return state.cartList.filter(item => item.isChecked)
	    },
	    // 选中的总数
	    selCount (state, getters) {
	      return getters.selCartList.reduce((sum, item) => sum + item.num, 0)
	    },
	    // 选中的总价
	    selPrice (state, getters) {
	      return getters.selCartList.reduce((sum, item) => {
	        return sum + item.num * item.price
	      }, 0).toFixed(2)
	    },
	    // 是否全选
	    isAllChecked (state) {
	      return state.cartList.every(item => item.isChecked)
	    }
	}
}